import axios from 'axios';
import { useRouter } from 'vue-router'
const router = useRouter()
import {useUserStore} from "@/stores/user.js"

const httpInstance=axios.create(
  {
    baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
    timeout:30000
  }
)


httpInstance.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
 let userStore = useUserStore();
 let token= userStore.userInfo.token
 if(token){
  config.headers['Authorization'] = 'Bearer ' + userStore.userInfo.token;
 }
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

httpInstance.interceptors.response.use(  (response)=> {
  // 对响应数据做点什么
  return response.data;
}, function (error) {
  console.log(error.state);
  if(error.state===200){
    ElMessage({
      message: 'Congrats, this is a success message.',
      type: 'success',
    })
  }else{
    if(error.state===401){
      ElMessage.error('登录过期，请重新登录')
      userStore.clearUserInfo()
      router.replace("/login")
    }
    ElMessage.error(error.response)
  }
  // 对响应错误做点什么
  return Promise.reject(error);
});
export default httpInstance;